package com.dubbo.gmail.provider.serviceImp;

import com.alibaba.dubbo.common.URL;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.dubbo.rpc.RpcContext;
import com.dubbo.gmail.api.message.RequestDubboFactory;
import com.dubbo.gmail.api.message.ResponseMessageVo;
import com.dubbo.gmail.api.message.impl.UserMatchRequest;
import com.dubbo.gmail.api.service.MatchRequestService;
import com.dubbo.gmail.api.service.MatchResponseService;
import com.dubbo.gmail.provider.ProviderApplication;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Service
@Component
public class MatchServiceImpl implements MatchRequestService, ApplicationContextAware {

    // 匹配队列
    private Map<Integer, ResponseMessageVo> messageVoMap = new HashMap<>();
    private ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();

    @Override
    public String addMatch(UserMatchRequest userMatchRequest) {
        ResponseMessageVo responseMessageVo = new ResponseMessageVo();
        RpcContext context = RpcContext.getContext();
        responseMessageVo.setRemoteAddress(RpcContext.getContext().getRemoteAddress());
        responseMessageVo.setPort(userMatchRequest.getPort());
        messageVoMap.putIfAbsent(userMatchRequest.getPlayerId(), responseMessageVo);
        return "add success";
    }

    private Runnable sendMessageRunnable = () -> {
        try {
            Iterator<ResponseMessageVo> iterator = messageVoMap.values().iterator();
            while (iterator.hasNext()) {
                ResponseMessageVo next = iterator.next();
                URL url = new URL("dubbo", next.getRemoteAddress().getAddress().getHostAddress(), next.getPort());
                MatchResponseService matchResponseService = RequestDubboFactory.buildRequestDubbo(MatchResponseService.class,
                        ProviderApplication.getApplicationContext(), url);
                matchResponseService.response(" ok");
                iterator.remove();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    };

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        scheduledExecutorService.scheduleAtFixedRate(sendMessageRunnable, 1, 1, TimeUnit.SECONDS);
    }
}
